package com.work.service.main.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.work.constant.ExceptionDescription;
import com.work.dto.main.*;
import com.work.entity.main.BulkTally;
import com.work.entity.main.TwoStockTally;
import com.work.mapper.main.BulkTallyMapper;
import com.work.service.main.IBulkTallyService;
import com.work.service.main.ITShipForecastService;
import com.work.service.main.ITallyMachineService;
import com.work.service.main.ITallyPassService;
import com.work.vo.main.*;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 散货外捣接口实现
 *
 * @author ：dujianyu
 * @since ：Created in 2024/5/9 9:51
 */
@Service
@AllArgsConstructor
public class BulkTallyServiceImpl extends BaseServiceImpl<BulkTallyMapper, BulkTally> implements IBulkTallyService {

    private ITallyPassService iTallyPassService;
    private ITallyMachineService tallyMachineService;
    private ITShipForecastService itShipForecastService;

    @Override
    public boolean submitBulkTally(BulkTallyAppSubmitDTO dto) {
        BulkTally entity = BeanUtil.copy(dto, BulkTally.class);
        if (Func.isNull(entity)) {
            throw new RuntimeException(ExceptionDescription.FUN_ERROR + "submitOneStockTally-BeanUtil.copy复制失败");
        }

        entity.setUpdateUserName(AuthUtil.getUserName());
        if (!Func.isNull(entity.getId())) {
            BulkTally detail = detail(entity.getId());
            if (!Func.isNull(detail.getIsCheck())) {
                return saveTallyBaseInfo(entity,dto);
            }
        }


        if (!itShipForecastService.addShipForecast(entity.getTransportShipId())) {
            throw new RuntimeException(ExceptionDescription.DB_ERROR + "添加理货船舶信息失败");
        }

        if (Func.isNull(entity.getId())) {
            entity.setCreateUserName(AuthUtil.getUserName());
        }

        entity.setCheckToTon(entity.getToTon());
        entity.setOriTon(entity.getOriTon());

        return saveTallyBaseInfo(entity, dto);
    }

    private TallyPassSubmitDTO setTallySubmitDTO(BulkTally bulkTally, BulkTallyAppSubmitDTO dto) {
        TallyPassSubmitDTO submitDTO = new TallyPassSubmitDTO();
        submitDTO.setTallyId(bulkTally.getId());
        submitDTO.setTransportShipId(bulkTally.getTransportShipId());
        submitDTO.setKeeper(dto.getKeeper());
        submitDTO.setKeeperName(dto.getKeeperName());
        submitDTO.setIsBedding(dto.getIsBedding());
        submitDTO.setIsCover(dto.getIsCover());
        submitDTO.setIsSafeProduction(dto.getIsSafeProduction());
        return submitDTO;
    }

    @Override
    public boolean removeBulkTally(Long id) {
        BulkTally bulkTally = detail(id);
        if (!Func.isNull(bulkTally.getIsCheck())) {
            throw new RuntimeException(ExceptionDescription.LOGIC_ERROR + "该工班已审核");
        }

        return super.deleteLogic(Func.toLongList(id.toString())) && iTallyPassService.removeByTallyId(id);
    }

    @Override
    public IPage<BulkTallyVO> selectBulkTallyHistoryPage(IPage<BulkTallyVO> page, BulkTallySearchDTO dto) {
        if ("Y".equals(dto.getPersonal())) {
            dto.setCreateUser(AuthUtil.getUserId());
        }
        List<BulkTallyVO> data = baseMapper.selectBulkTallyHistoryList(dto, page);
        return page.setRecords(data);
    }

    @Override
    public IPage<BulkTallyCheckVO> selectCheckPage(IPage<BulkTallyCheckVO> page, BulkTallySearchDTO dto) {
        List<BulkTallyCheckVO> data = baseMapper.selectCheckList(dto, page);
        return page.setRecords(data);
    }

    @Override
    public boolean correctTon(BulkTallyCorrectSubmitDTO dto) {
        BulkTally oldTally = detail(dto.getId());
        if (Func.isNull(oldTally.getIsCheck())) {
            oldTally.setIsCheck("N");
        }
        oldTally.setCheckOriTon(dto.getCheckOriTon());
        if (!Func.isNull(dto.getCheckToTon())) {
            oldTally.setCheckToTon(dto.getCheckToTon());
        }
        oldTally.setCheckType(dto.getCheckType());
        oldTally.setCheckReason(dto.getCheckReason());
        oldTally.setChecker(AuthUtil.getUserId());
        oldTally.setCheckerName(AuthUtil.getUserName());
        return super.saveOrUpdate(oldTally);
    }

    @Override
    public String changeIsCheck(String id) {
        BulkTally detail = detail(Func.toLong(id));

        BulkTally update = new BulkTally();
        update.setId(Func.toLong(id));
        if ("Y".equals(detail.getIsCheck())) {
            update.setIsCheck("N");
        } else {
            update.setIsCheck("Y");
            update.setIsEdit("N");
        }
        update.setChecker(AuthUtil.getUserId());
        update.setCheckerName(AuthUtil.getUserName());
        if (!super.saveOrUpdate(update)) {
            throw new RuntimeException(ExceptionDescription.DB_ERROR + "更新检算状态失败");
        }
        return update.getIsCheck();
    }

    @Override
    public IPage<BulkTallyUnlockVO> selectUnlockPage(IPage<BulkTallyUnlockVO> page, BulkTallySearchDTO dto) {
        List<BulkTallyUnlockVO> data = baseMapper.selectUnlockList(dto, page);
        return page.setRecords(data);
    }

    @Override
    public String changeIsEdit(String id) {
        BulkTally detail = detail(Func.toLong(id));

        BulkTally update = new BulkTally();
        update.setId(Func.toLong(id));
        if("Y".equals(detail.getIsCheck())) {
            throw new RuntimeException(ExceptionDescription.LOGIC_ERROR + "检算已完成");
        }
        if ("Y".equals(detail.getIsEdit()) || Func.isNull(detail.getIsEdit())) {
            update.setIsEdit("N");
        } else {
            update.setIsEdit("Y");
        }
        update.setEditChangeUser(AuthUtil.getUserId());
        update.setEditChangeUserName(AuthUtil.getUserName());
        if (!super.saveOrUpdate(update)) {
            throw new RuntimeException(ExceptionDescription.DB_ERROR + "更新可编辑状态失败");
        }
        return update.getIsEdit();
    }

    @Override
    public BulkTallyUnlockDetailVO selectBulkDetail(BulkTallySearchDTO dto) {
        if (Func.isNull(dto.getId())) {
            throw new RuntimeException(ExceptionDescription.NO_PARAM + "缺少主键ID");
        }
        return baseMapper.selectBulkDetail(dto);
    }

    @Override
    public IPage<BulkTallySearchExportVO> selectTallySearchExportPage(IPage<BulkTallySearchExportVO> page, BulkTallySearchDTO dto) {
        List<BulkTallySearchExportVO> data = baseMapper.selectTallySearchExportList(dto, page);
        return page.setRecords(data);
    }

    @Override
    public TotalPieceTonVO selectTallySearchExportTotal(BulkTallySearchDTO dto) {
        return baseMapper.selectTallySearchExportTotal(dto);
    }

    private BulkTally detail(Long id) {
        QueryWrapper<BulkTally> oldTallyQuery = new QueryWrapper<>();
        oldTallyQuery.lambda()
                .eq(BulkTally::getId, id)
                .eq(BulkTally::getIsDeleted, 0)
                .last("limit 1");
        BulkTally bulkTally = baseMapper.selectOne(oldTallyQuery);
        if (Func.isNull(bulkTally)) {
            throw new RuntimeException(ExceptionDescription.DB_ERROR + "散货外捣理货记录不存在");
        }
        return bulkTally;
    }

    private boolean saveTallyBaseInfo(BulkTally entity, BulkTallyAppSubmitDTO dto) {
        if (!super.saveOrUpdate(entity)) {
            throw new RuntimeException(ExceptionDescription.DB_ERROR + "保存散货外捣失败");
        }
        return iTallyPassService.submitTallyPass(setTallySubmitDTO(entity, dto)) && tallyMachineService.submitTallyMachineBatch(entity.getId(), dto.getMachineList());
    }
}
